﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CPPEI.Coolzon.Core;
using CPPEI.Coolzon.Core.Repositories;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

namespace CPPEI.Coolzon.ManagementCenter
{
    public partial class UserList : System.Web.UI.Page
    {
        private string userId;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
               LoadData();
            }
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        public void LoadData()
        {
            using (DbContext context = new DbContext())
            {
                IUserRepository userRepository = RepositoryFactory.Create<IUserRepository>();

                PagedList<CPPEI.Coolzon.Core.Data.User> userList = userRepository.GetUserList(context, 0, int.MaxValue);
                gvUserList.DataSource = userList.DataList;
                gvUserList.DataBind();
            }
        }

        protected void gvUserList_RowEditing(object sender, GridViewEditEventArgs e)
        {
            userId = ((Label)gvUserList.Rows[e.NewEditIndex].FindControl("lblId")).Text.Trim();
            Response.Redirect("EditUser.aspx?Id=" + userId, false);
        }

        protected void gvUserList_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            using (DbContext context = new DbContext())
            {
                IUserRepository userRepository = RepositoryFactory.Create<IUserRepository>();
                IAssignedPrivilegeRepository iAssignedPrivilegeRepository = RepositoryFactory.Create<IAssignedPrivilegeRepository>();
                string Id = ((Label)gvUserList.Rows[e.RowIndex].FindControl("lblId")).Text.Trim();
                CPPEI.Coolzon.Core.Data.User user = new CPPEI.Coolzon.Core.Data.User();
                user.Id = new Guid(Id);

                if (userRepository.RemoveUser(context, user) && iAssignedPrivilegeRepository.RemoveAssignedPrivilege(context, new Guid(Id)))
                {
                    LoadData();
                }
            }
        }

      

        protected void gvUserList_RowPrivileges(object sender, GridViewUpdateEventArgs e)
        {
            userId = ((Label)gvUserList.Rows[e.RowIndex].FindControl("lblId")).Text.Trim();
            Response.Redirect("Privileges.aspx?userId=" + userId, false);
        }

        public string GetUserId()
        {
            return userId;
        }

        protected void _ctlAddUser_Click(object sender, EventArgs e)
        {
            Response.Redirect("AddUser.aspx", false);
        }
    }
}